package com.supor.aiot.mine.ui.setting;

import android.annotation.SuppressLint;
import android.app.Application;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.supor.aiot.common.app.SuporApplication;
import com.supor.aiot.common.base.BaseViewModel;
import com.supor.aiot.common.entity.Result;
import com.supor.aiot.mine.api.AppReleaseImpl;
import com.supor.aiot.mine.bean.AppReleaseItem;
import com.supor.aiot.mine.bean.BossTAppParams;

import java.util.List;

public class VersionUpdateViewModel extends BaseViewModel {

    private MutableLiveData<Result> latestResult = new MutableLiveData<>();

    public MutableLiveData<Result> getLatestResult() {
        return latestResult;
    }

    public VersionUpdateViewModel(@NonNull Application application) {
        super(application);
    }

    @SuppressLint("CheckResult")
    public void getLatestVersion() {
        AppReleaseImpl.getInstance().getAppReleaseListPage(BossTAppParams.appOs,
                BossTAppParams.appType, BossTAppParams.page, BossTAppParams.limit).subscribe(result -> {
                    if (result.isSuccess()) {
                        String latestVersion = null;
                        boolean isLatestVer = false;
                        List<AppReleaseItem> appReleaseItems = result.data.rows;
                        if (appReleaseItems != null && appReleaseItems.size() > 0) {
                            latestVersion = appReleaseItems.get(appReleaseItems.size() - 1).appVersion;
                        }
                        if (SystemUtils.getVerName(SuporApplication.getBaseApplication()).equals(latestVersion)) {
                            isLatestVer = true;
                        }
                        latestResult.setValue(new Result.Success(isLatestVer));
                    } else {
                        latestResult.setValue(new Result.Error("getLatestVersion failed"));
                    }
        }, throwable -> {
            Logc.e("getLatestVersion: " + throwable);
            latestResult.setValue(new Result.Error(new Exception(throwable)));
        });
    }
}
